package com.miaoquan.mqcommon.api;

import com.github.pagehelper.PageInfo;
import lombok.Data;
import org.springframework.data.domain.Page;

import java.util.List;

/**
 * 分页数据封装类
 *
 * @author Fa
 * @date 2020-03-29 16:25
 */
@Data
public class CommonPage<T> {

    private Integer pageNum;
    private Integer pageSize;
    private Integer totalPage;
    private Long total;
    private List<T> list;


    /**
     * 将PageHelper分页后的list转为分页信息
     */
    public static <T> CommonPage<T> restPage(List<T> list) {
        CommonPage<T> result = new CommonPage<T>();
        PageInfo<T> pageInfo = new PageInfo<T>(list);
        result.setTotalPage(pageInfo.getPages());
        result.setPageNum(pageInfo.getPageNum());
        result.setPageSize(pageInfo.getPageSize());
        result.setTotal(pageInfo.getTotal());
        result.setList(pageInfo.getList());
        return result;
    }

    /**
     * 将PageHelper分页后的list转为分页信息
     */
    public static <T> CommonPage<T> restPage(List<T> list, int pageNum, int pageSize) {
        return CommonPage.restPage(CommonPage.afterPage(list, pageNum, pageSize));
    }

    /**
     * 将PageHelper分页后的list转为分页信息
     */
    public static <T> CommonPage<T> restPage(List<T> list, int pageNum, int pageSize, int total) {
        return CommonPage.restPage(CommonPage.afterPage(list, pageNum, pageSize, total));
    }

    /**
     * 将SpringData分页后的list转为分页信息
     */
    public static <T> CommonPage<T> restPage(Page<T> pageInfo) {
        CommonPage<T> result = new CommonPage<T>();
        result.setTotalPage(pageInfo.getTotalPages());
        result.setPageNum(pageInfo.getNumber());
        result.setPageSize(pageInfo.getSize());
        result.setTotal(pageInfo.getTotalElements());
        result.setList(pageInfo.getContent());
        return result;
    }


    public static <T> com.github.pagehelper.Page<T> afterPage(List<T> pageList, int pageNum, int pageSize) {
        com.github.pagehelper.Page<T> page = new com.github.pagehelper.Page<>(pageNum, pageSize);
        page.addAll(pageList);
        if (!page.isCount()) {
            page.setTotal(-1);
        } else if ((page.getPageSizeZero() != null && page.getPageSizeZero()) && page.getPageSize() == 0) {
            page.setTotal(pageList.size());
        } else if (page.isOrderByOnly()) {
            page.setTotal(pageList.size());
        }
        return page;
    }

    /**
     * @param total 总记录数
     */
    public static <T> com.github.pagehelper.Page<T> afterPage(List<T> pageList, int pageNum, int pageSize, int total) {
        com.github.pagehelper.Page<T> page = afterPage(pageList, pageNum, pageSize);
        page.setTotal(total);
        page.setPages((int) (page.getTotal() / page.getPageSize()));
        return page;
    }


}
